package cn.catsdad.auth.config;

import cn.catsdad.auth.util.SecurityUtil;
import cn.catsdad.vo.LoginUser;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.Authentication;

import java.util.Optional;

/**
 * JPA操作人id填充配置
 *
 * @author xuyonglong
 * @version V1.0 2023/4/21
 */
@Configuration
public class JpaUserIdAuditorConfig implements AuditorAware<Long> {
    @Override
    public Optional<Long> getCurrentAuditor() {
        Authentication authentication = SecurityUtil.getAuthentication();
        //请求无token时用户会被填充为字符串“anonymousUser”
        if (authentication != null && !authentication.getPrincipal().equals("anonymousUser")) {
            LoginUser user = (LoginUser) authentication.getPrincipal();
            return Optional.of(user.getUserId());
        }
        return Optional.empty();
    }
}
